<!-- 创建作业或修改作业信息 -->
<template>
  <div class="secong-box">
    <div>
      <el-card shadow="never">
        <el-row :gutter="50">
          <el-col :span="1">
            <p class="tag">标题:</p>
          </el-col>
          <el-col :span="9">
            <el-input
              :required="true"
              type="text"
              placeholder="请输入作业标题"
              v-model="taskinfo.title"
              maxlength="30"
              show-word-limit
            >
            </el-input>
          </el-col>
        </el-row>
        <el-row :gutter="50">
          <el-col :span="1">
            <p class="tag">类型:</p>
          </el-col>
          <el-col :span="6" class="col-tag">
            <el-radio v-model="taskinfo.kind" label="0">普通作业</el-radio>
            <el-radio v-model="taskinfo.kind" label="1">考试</el-radio>
          </el-col>
          <el-col :span="1" :offset="12">
            <el-button
              type="primary"
              :loading="isloading"
              @click="CreateTask()"
              >{{ buttonText.taskBtnText }}</el-button
            >
          </el-col>
        </el-row>
      </el-card>

      <el-card shadow="never" class="cml-box" v-if="ispreview">
        <el-row>
          <el-col :span="1"
            ><a class="active_a" @click="setPreview(1)" style="float: right"
              >返回</a
            ></el-col
          >
        </el-row>
        <el-row v-for="(item, index) in taskinfo.topic" :key="index">
          <el-row>
            <el-row>
              <el-col :span="2" :offset="3"
                ><p>
                  {{ index + 1 }}.({{
                    topicButtonType[item.kind % 5].substring(0, 2)
                  }}-{{ item.sorce }}分)
                </p></el-col
              >
              <el-col :span="16">
                <div v-html="item.topicSubject"></div>
              </el-col>
            </el-row>

            <el-row v-if="item.kind < 2">
              <el-row v-for="(op, i) in item.topicOptions" :key="i">
                <el-col :span="1" :offset="5" v-if="item.kind < 2">
                  <el-button type="info" size="mini" disabled circle>{{
                    String.fromCharCode(65 + i)
                  }}</el-button>
                </el-col>
                <el-col :span="13">
                  <div>
                    <div v-html="op"></div>
                  </div>
                </el-col>
              </el-row>
            </el-row>
            <el-row>
              <el-col :span="1" :offset="5" v-if="item.kind < 3">
                <label>答案:</label></el-col
              >
              <el-col :span="1" :offset="5" v-else> <p>答案:</p></el-col>
              <el-col :span="13" v-if="item.kind < 2">
                <span
                  v-for="(an, i) in item.answers"
                  :key="i"
                  v-text="an"
                ></span>
              </el-col>
              <el-col :span="13" v-if="item.kind == 2">
                <span v-if="item.answers[0] == 0">错</span>
                <span v-else>对</span>
              </el-col>
              <el-col :span="13" v-if="item.kind > 2">
                <div v-for="(an, i) in item.answers" :key="i" v-html="an">
                  <!-- <div>{{i+1}}:</div>
                  <div  style="float:left"></div> -->
                </div>
              </el-col>
            </el-row>
          </el-row>

          <hr class="hr" />
        </el-row>
      </el-card>

      <el-row :gutter="8" class="cml-box" v-if="show">
        <el-col :span="6">
          <el-card class="cml-task-1" shadow="never">
            <div>
              <span class="tag">题量:</span>{{ taskinfo.count }}
              <span class="tag">总分:</span>{{ taskinfo.sorceSum }}
              <a class="active_a" @click="setPreview(0)" style="float: right"
                >预览</a
              >
            </div>
            <br />
            <div>
              <div>
                <div
                  v-for="(item, index) in taskinfo.topic"
                  :key="index"
                  class="cml-box"
                >
                  <!-- <span class="tag-1">单选</span> -->
                  <el-col :span="1"
                    ><span>{{ index + 1 }}.</span></el-col
                  >
                  <!-- <el-link :underline="false">无下划线</el-link> -->
                  <el-col :span="22" :offset="1">
                    <a
                      class="cml-span"
                      :class="{ active_a: index == a_index }"
                      :title="
                        item.topicSubject
                          .replace(/<[^>]+>/g, '')
                          .replace(/&nbsp;/g, ' ')
                      "
                      @click.prevent="echoTopic(index)"
                      v-text="
                        item.topicSubject
                          .replace(/<[^>]+>/g, '')
                          .replace(/&nbsp;/g, ' ')
                      "
                    >
                    </a></el-col
                  ><br />
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-card shadow="never">
            <span class="tag">题库添加:</span>
            <el-button
              size="mini"
              round
              v-for="(item, index) in topicButtonType"
              @click="dbTopic(index)"
              :key="index"
              >{{ item }}</el-button
            >
            <el-button type="warning" size="mini" round @click="manualButton()"
              >手动添加</el-button
            >
          </el-card>

          <!--数据库添题的详情框-->
          <el-card class="cml-box" shadow="never" v-if="isdbButton">
            dcd
          </el-card>

          <!--手动添题详情框-->
          <el-card class="cml-box" shadow="never" v-if="ismanualButton">
            <div style="margin-bottom: 20px">
              <span class="tag">题型:</span>
              <el-radio-group
                v-model="cusmer.kind"
                @change="cumserTopicSelect"
                :disabled="isdisabled"
              >
                <el-radio label="0">单选</el-radio>
                <el-radio label="1">多选</el-radio>
                <el-radio label="2">判断</el-radio>
                <el-radio label="3">填空</el-radio>
                <el-radio label="4">综合</el-radio>
              </el-radio-group>
            </div>
            <div>
              <el-col :span="1"><el-tag type="success">分数</el-tag></el-col>

              <el-col :span="3" :offset="1">
                <i
                  v-if="cusmer.sorce > 1"
                  class="el-icon-minus"
                  @click="cusmer.sorce--"
                ></i>
                <el-tag type="info">{{ cusmer.sorce }}分</el-tag>
                <i
                  v-if="cusmer.sorce < 50"
                  class="el-icon-plus"
                  @click="cusmer.sorce++"
                ></i>
              </el-col>
              <el-col :span="2" :offset="14">
                <el-button
                  type="danger"
                  size="small"
                  :disabled="!isdisabled"
                  @click="deleteTopic()"
                  :loading="isdeleteloading"
                  >移除</el-button
                >
              </el-col>
            </div>
            <br />

            <div class="cml-box-1">
              <p class="tag">
                题干:（如需添加图片先点击上传图片，在点击图片图标，可设置图片大小）
              </p>

              <div @click="indexControll = -2">
                <div
                  class="textarea"
                  type="textarea"
                  placeholder="题干信息"
                  v-html="cusmer.topicSubject"
                  v-if="!(indexControll == -2)"
                ></div>

                <tinymce
                  v-else
                  v-model="cusmer.topicSubject"
                  :height="100"
                  menubar=""
                ></tinymce>
              </div>
            </div>

            <div v-if="cusmer.kind == 0 || cusmer.kind == 1">
              <p class="tag">选项</p>

              <el-row
                v-for="(item, index) in cusmer.topicOption"
                class="cml-box"
                :key="index"
                style="margin-bottom: 20px"
              >
                <el-col :span="1"
                  ><el-button
                    :class="{ activeChoice: choiceAnswer[index] === true }"
                    circle
                    @click="choiceTopicAnswer(index)"
                    title="设为答案"
                    >{{ String.fromCharCode(65 + index) }}</el-button
                  ></el-col
                >
                <el-col :span="22" :offset="1">
                  <div @click="indexControll = index">
                    <el-input
                      class="textarea"
                      type="textarea"
                      :placeholder="'第' + (index + 1) + '空/选项'"
                      v-html="cusmer.topicOption[index]"
                      v-if="!(indexControll == index)"
                    >
                    </el-input>

                    <tinymce
                      v-else
                      v-model="cusmer.topicOption[index]"
                      :height="100"
                      menubar=""
                    ></tinymce>
                  </div>
                </el-col>
              </el-row>
              <br />
              <el-col :span="6" :offset="2">
                <el-button type="info" size="mini" round @click="addOption()"
                  >增加选项</el-button
                >
                <el-button type="info" size="mini" round @click="deleteOption()"
                  >移除选项</el-button
                >
              </el-col>
            </div>

            <div v-if="cusmer.kind == 2">
              <el-row class="cml-box-1">
                <el-col :span="1"><span class="tag">答案:</span></el-col>
                <el-col :span="22" :offset="1">
                  <el-radio-group v-model="cusmer.answer[0]">
                    <el-radio label="1">对</el-radio>
                    <el-radio label="0">错</el-radio>
                  </el-radio-group>
                </el-col>
              </el-row>
            </div>

            <!-- <p class="tag">答案</p> -->
            <div v-if="cusmer.kind == 3 || cusmer.kind == 4">
              <p class="tag">答案:</p>
              <el-row
                class="cml-box"
                v-for="(item, index) in cusmer.answer"
                :key="index"
              >
                <!-- <span class="tag">答案:</span> -->
                <!-- <p class="tag">答案:</p> -->
                <el-col :span="22" :offset="2">
                  <div @click="indexControll = index">
                    <el-input
                      class="textarea"
                      type="textarea"
                      placeholder="请输入内容"
                      v-html="cusmer.answer[index]"
                      v-if="!(indexControll == index)"
                    >
                    </el-input>

                    <tinymce
                      v-else
                      v-model="cusmer.answer[index]"
                      :height="100"
                      menubar=""
                    ></tinymce>
                  </div>
                </el-col>
              </el-row>
              <br />
              <el-col :span="6" :offset="2" v-if="cusmer.kind == 3">
                <el-button type="info" size="mini" round @click="addOption()"
                  >增加填空</el-button
                >
                <el-button type="info" size="mini" round @click="deleteOption()"
                  >移除填空</el-button
                >
              </el-col>
            </div>

            <div class="cml-box-1" style="margin-bottom: 88px">
              <el-col :offset="11">
                <el-button
                  type="primary"
                  @click="addTopicAndDB()"
                  :loading="isaddloading"
                  >{{ buttonText.topicBtnText }}</el-button
                >
                <span class="tag"
                  >此操同时作会将题目添加到题库，请检查题目的完整性</span
                >
              </el-col>
            </div>
          </el-card>

          <!-- <div v-if="cusmer.kind == 5">回显</div> -->
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import Tinymce from "../../../../components/Tinymce/index.vue";
import MultiUpload from "../../../common/upload/multiUpload.vue";

//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Tinymce, MultiUpload },

  data() {
    //这里存放数据
    return {
      ispreview: false,
      a_index: -1,
      indexControll: -1,
      show: false,
      buttonText: {
        taskBtnText: "立即创建",
        topicBtnText: "添加",
      },
      indexTopic: "",
      isloading: false,
      isdeleteloading: false,
      isaddloading: false,
      topicButtonType: ["单选题", "多选题", "判断题", "填空题", "综合题"],
      choiceAnswer: [false, false],
      ismanualButton: false, //手动添题框是否显示
      isdisabled: false,
      isdbButton: true, //数据库添题框是否显示
      topicIdandSocre: [],
      //手动添题的题目信息
      cusmer: {
        sorce: 5,
        id: "",
        topicSubject: "",
        topicOption: ["", ""],
        answer: [""],
        kind: "0",
        courseId: "",
      },
      //作业信息
      taskinfo: {
        id: "",
        count: "",
        sorceSum: "",
        title: "",
        kind: "0",
        status: "",
        topic: "",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    setPreview(val) {
      if (val == 0) {
        this.ispreview = true;
        this.show = false;
      }
      if (val == 1) {
        this.ispreview = false;
        this.show = true;
      }
    },
    handlerToipcAndSorce() {
      var s = "";
      for (let index = 0; index < this.topicIdandSocre.length; index++) {
        if (index == 0) {
          s += this.topicIdandSocre[0].id + "-" + this.topicIdandSocre[0].sorce;
        } else {
          s +=
            "," +
            this.topicIdandSocre[index].id +
            "-" +
            this.topicIdandSocre[index].sorce;
        }
      }
      return s;
    },
    setToipcAndSorce() {
      var topic = this.taskinfo.topic;
      this.topicIdandSocre = [];
      for (let index = 0; index < topic.length; index++) {
        this.topicIdandSocre.push({
          id: topic[index].id,
          sorce: topic[index].sorce,
        });
      }
    },
    //增加选项框
    addOption() {
      this.cusmer.topicOption.push("");
      this.choiceAnswer.push(false);
      this.cusmer.answer.push("");
      // this.cusmer.topicOption.splice(3);
    },
    deleteOption() {
      // this.cusmer.topicOption.pop();
      this.choiceAnswer.pop();
      this.cusmer.answer.pop();
      this.cusmer.topicOption.splice(this.cusmer.topicOption.length - 1, 1);
    },
    //点击回显topic
    echoTopic(val) {
      this.a_index = val;
      // this.Tinymce.destroyed();
      var topic = this.taskinfo.topic[val];
      // this.initcusmer(topic.kind);
      this.isdbButton = false;
      this.ismanualButton = true;
      this.isdisabled = true;
      this.buttonText.topicBtnText = "修改";
      this.cusmer = {
        id: topic.id,
        topicSubject: topic.topicSubject,
        topicOption: topic.topicOptions,
        answer: topic.answers,
        kind: topic.kind,
        sorce: topic.sorce,
        courseId: "",
      };
      this.choiceAnswer = [false, false];
      this.getTaskDetil();

      if (topic.kind == "0" || topic.kind == "1")
        for (var index = 0; index < topic.answers.length; index++) {
          var i = topic.answers[index].charCodeAt(0) - 65;
          this.$set(this.choiceAnswer, i, true);
        }
      this.indexTopic = this.cusmer.topicOption.length;
    },
    //获取作业的详细信息///edu-task/task/topic/1395060863735459842
    getTaskDetil() {
      this.$http({
        url: this.$http.adornUrl(
          `/edu-task/task/topic/${this.$route.query.taskId}`
        ),
        method: "get",
        data: {},
      }).then((data) => {
        if (data && data.data.code == 20000) {
          console.log("task:", data.data.data.data);
          this.taskinfo = data.data.data.data;
          this.taskinfo.kind = this.taskinfo.kind + "";
          this.setToipcAndSorce();
          for (let index = 0; index < this.taskinfo.topic.length; index++) {
            if (this.taskinfo.topic[index].id == this.cusmer.id) {
              this.a_index = index;
            }
          }
        } else {
          this.$message.error("获取数据失败");
        }
      });
    },
    //点击手动添题按钮
    manualButton() {
      this.a_index = -1;
      this.isdbButton = false;
      this.ismanualButton = true;
      this.isdisabled = false;
      this.initcusmer("0");
      this.buttonText.topicBtnText = "添加";
    },
    //初始化cusmer
    initcusmer(value) {
      var cusmerNew = {
        sorce: 3,
        id: "",
        topicSubject: "",
        topicOption: ["", ""],
        answer: [""],
        kind: value,
        courseId: "",
      };
      this.cusmer = cusmerNew;
      // this.cusmer = Object.assign({}, cusmerNew);
      this.choiceAnswer = [false, false];
    },
    //手动添题题型选择
    cumserTopicSelect(value) {
      //将cusmer的key初始化为空
      this.initcusmer(value);
      // this.cusmer.topicOption=[];
    },
    //单选，多选答案配置
    choiceTopicAnswer(index) {
      //判断是单选还是多选
      //单选答案只能有一个
      if (this.cusmer.kind == 0) {
        if (this.choiceAnswer[index] == true) {
          this.$set(this.choiceAnswer, index, false);
        } else {
          for (var i = 0; i < this.choiceAnswer.length; i++) {
            this.$set(this.choiceAnswer, i, false);
          }
          this.$set(this.choiceAnswer, index, true);
        }
      }

      //多选答案可能有多个
      if (this.cusmer.kind == 1) {
        if (this.choiceAnswer[index] == true) {
          this.$set(this.choiceAnswer, index, false);
        } else {
          this.$set(this.choiceAnswer, index, true);
        }
      }
      //设置答案
      this.cusmer.answer = [];
      var j = 0;
      for (var i = 0; i < this.choiceAnswer.length; i++) {
        if (this.choiceAnswer[i] == true) {
          this.$set(this.cusmer.answer, j, String.fromCharCode(65 + i));
          j = j + 1;
        }
      }
      // this.$forceUpdate(); //强制刷新
    },

    //去数据库查题,type题目类型
    dbTopic(type) {
      this.a_index = -1;
      this.ismanualButton = false;
      this.isdbButton = true;
      //查数据库该科目下的单选题
    },

    //操作题目
    operTopic() {
      this.$http({
        url: this.$http.adornUrl(`/edu-task/task`),
        method: "put",
        data: this.$http.adornData(
          {
            id: this.taskinfo.id,
            title: this.taskinfo.title,
            kind: this.taskinfo.kind,
            topic: this.handlerToipcAndSorce(),
          },
          false
        ),
      }).then((data) => {
        if (data) {
          this.getTaskDetil();
          this.isloading = false;
          this.isdisabled = true;
          if (this.a_index >= 0) {
            this.buttonText.topicBtnText = "添加";
          } else {
            this.buttonText.topicBtnText = "修改";
          }

          return true;
        } else {
          this.$message.error("题目操作失败！");
          return false;
        }
      });
    },

    //移除题目
    deleteTopic() {
      this.isdeleteloading = true;
      for (let index = 0; index < this.topicIdandSocre.length; index++) {
        if (this.topicIdandSocre[index].id == this.cusmer.id) {
          this.topicIdandSocre.splice(index, 1);
          break;
        }
      }
      if (this.operTopic()) {
        this.initcusmer(this.cusmer.kind);
        this.isdeleteloading = false;
      } else {
        this.isdeleteloading = false;
      }
    },

    //手动添题的添加按钮s
    addTopicAndDB() {
      if (this.chickCusmerTopic()) {
        this.isaddloading = true;
        this.$http({
          url: this.$http.adornUrl(`/edu-topic/addTopic`),
          method: "post",
          data: this.$http.adornData(
            {
              id: this.cusmer.id,
              topicSubject: this.cusmer.topicSubject,
              topicOptions: this.cusmer.topicOption,
              answers: this.cusmer.answer,
              kind: this.cusmer.kind,
              courseId: this.$route.query.courseid,
            },
            false
          ),
        }).then((data) => {
          if (data && data.data.code == 20000) {
            let index = 0;
            for (; index < this.topicIdandSocre.length; index++) {
              if (this.topicIdandSocre[index].id == data.data.data.topicId) {
                this.topicIdandSocre[index].sorce = this.cusmer.sorce;
                break;
              }
            }
            if (index == this.topicIdandSocre.length) {
              this.topicIdandSocre.push({
                id: data.data.data.topicId,
                sorce: this.cusmer.sorce,
              });
            }
            this.cusmer.id = data.data.data.topicId;

            this.operTopic();
            this.isaddloading = false;
          } else {
            this.$message.error("题目添加&修改失败");
          }
        });
      } else {
        // this.$message.error("题目信息不完整");
      }
    },

    //检查手动添题 题目完整性
    chickCusmerTopic() {
      if (this.taskinfo.title == "" || this.taskinfo.title == null) {
        this.$message.error("未输入作业名称！");
        return false;
      }
      if (!this.cusmer.topicSubject) {
        this.$message.error("未输入题干！");
        return false;
      }

      if (this.cusmer.kind == 0 || this.kind == 1) {
        if (!this.cusmer.topicOption[0] && !this.cusmer.topicOption[1]) {
          this.$message.error("未输选择题型！");
          return false;
        }
      } else {
        this, (this.cusmer.topicOption = []);
      }

      if (!this.cusmer.answer[0]) {
        this.$message.error("未输设置答案！");
        return false;
      }

      return true;
    },
    //创建作业
    CreateTask() {
      //检查标题和类型是否填写
      // alert(this.taskinfo.title+"S"+this.taskinfo.kind);
      if (
        this.taskinfo.title != null &&
        this.taskinfo.title != "" &&
        this.taskinfo.kind != null
      ) {
        this.isloading = true;

        this.$http({
          url: this.$http.adornUrl(`/edu-task/task`),
          method: "put",
          data: this.$http.adornData(
            {
              id: this.taskinfo.id,
              title: this.taskinfo.title,
              kind: this.taskinfo.kind,
              teacherId: this.$store.state.user.id,
              courseId: this.$route.query.courseid,
            },
            false
          ),
        }).then((data) => {
          if (data) {
            this.isloading = false;
            // this.getTaskDetil();
            this.$router.push({
              name: "teachertask",
              query: {
                courseid: this.$route.query.courseid,
                courseName: this.$route.query.courseName,
              },
            });
          } else {
            this.$message.error("作业创建失败！");
          }
        });
      } else {
        this.$message.error("请输入作业标题");
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (this.$route.query.taskId) {
      this.show = true;
      this.buttonText = {
        taskBtnText: "更改信息",
        topicBtnText: "修改",
      };
      this.getTaskDetil();
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.secong-box {
  //   border: 1px red solid;
}
.tag {
  color: #141518; //#909399
  padding: 0 10px;
  font-size: 13px;
  white-space: nowrap;
}
.tag-1 {
  color: #909399; //#909399
  padding: 0 10px;
  font-size: 7px;
  white-space: nowrap;
}
.col-tag {
  vertical-align: middle;
  padding-top: 12px;
}
.cml-box {
  margin-top: 10px;
}
.cml-box-1 {
  margin-top: 40px;
}
.cml-task-1 {
  height: 100%;
}
.activeChoice {
  background-color: palegreen;
}
.cml-span {
  margin-top: 1px;
  margin-right: 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
a {
  font-size: 13px;
  font-family: "Helvetica Neue";
  color: #606266;
}
.textarea {
  width: 100%;
  border: #dcdfe6 1px solid;
  padding: 5px 5px 5px 5px;
  min-height: 50px;
}
.active_a {
  color: #17b3a3;
}
.hr {
  // border: #dcdfe6 1px solid;
  align-items: center;
  width: 88%;
  background-color: #dcdfe6;
  size: 1;
}
</style>